package com.ruoyi.system.service.impl;


import com.ruoyi.system.domain.SysCity;
import com.ruoyi.system.mapper.CityMapper;
import com.ruoyi.system.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author silence.Z
 */
@Service
@Transactional
public class CityServiceImpl implements ICityService {

	@Autowired
	private CityMapper cityMapper;

	@Override
	public SysCity selectTree() {
		List<SysCity> collect = null;
		List<SysCity> structureVoList = cityMapper.selectTree();
		collect = structureVoList;
		SysCity vo = new SysCity("0", "0", "中国", new ArrayList<SysCity>());
		collect.add(vo);
		// 设置根节点
		SysCity root = null;
		Map<String, SysCity> structureVoMap = new HashMap<>();
		// 将每个对象放入map，方便取值
		collect.forEach(e -> structureVoMap.put(e.getId(), e));

		for (SysCity sv : collect) {
			if ("0".equals(sv.getId())) {
				root = sv;
				continue;
			}
			// 获取对应的上级对象
			SysCity structureVo = structureVoMap.get(sv.getPid());
			if (structureVo != null) {
				structureVo.getChildren().add(sv);
			}

		}
		return root;
	}

	public List<SysCity> GuoLv(List<SysCity> structureVoList, String code) {

		SysCity structure = structureVoList.stream().filter(e -> code.equals(e.getId())).findAny().orElse(null);
		List<SysCity> collect = structureVoList.stream().filter(e -> e.getId().length() != code.length()).collect(Collectors.toList());
		collect.add(structure);
		if (structure.getId().length() > 6) {
			List<SysCity> structureVos = GuoLv(collect, structure.getPid());
			return structureVos;
		}
		return collect;
	}

	/**
	 * 新增城市
	 *
	 * @param sysCity 城市
	 * @return 结果
	 */
	@Override
	public int insertSysCity(SysCity sysCity)
	{
		//根据pid获取所有pid相同的城市id
		SysCity city2 = new SysCity();
		city2.setPid(sysCity.getPid());
		Integer id = cityMapper.selectMaxid(city2);
		sysCity.setId(String.valueOf(id+1));
		return cityMapper.insertSysCity(sysCity);
	}

	/**
	 * 修改城市
	 *
	 * @param sysCity 城市
	 * @return 结果
	 */
	@Override
	public int updateSysCity(SysCity sysCity)
	{
		return cityMapper.updateSysCity(sysCity);
	}

	/**
	 * 删除城市信息
	 *
	 * @param id 城市主键
	 * @return 结果
	 */
	@Override
	public int deleteSysCityById(Long id)
	{
		return cityMapper.deleteSysCityById(id);
	}

	@Override
	public List<SysCity> selectCityList(SysCity city) {
		return cityMapper.selectSysCityList(city);
	}
}
